<template>
  <div class="p-2">
    <a-modal v-model:visible="props.visible" title="添加指令" @update:visible="handleCancel" @cancel="handleCancel">
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleOk">确认</a-button>
      </template>
      <a-form ref="userFormRef"  :model="formState"  :rules="rules" >
        <a-form-item name="name" label="按钮名称" >
          <a-input v-model:value="formState.name" placeholder="请输入按钮名称" showCount="true"  maxlength=10 />
        </a-form-item>
        <a-form-item label="按钮图标:" name="icon">
          <icon-select v-model:value="formState.icon" placeholder="点击请选择图标"></icon-select>
        </a-form-item>
        <a-form-item name="descr" label="指令内容">
          <a-textarea v-model:value="formState.descr" placeholder="请输入指令内容" showCount="true" maxlength=100 />
        </a-form-item>

      </a-form>
    </a-modal>
  </div>
</template>

<script setup name="AiAppQuickCommandModal">

import {onMounted, ref} from 'vue';


    const props = defineProps({
      visible: Boolean,
      data: Object
    });

    const rules = {
      name: [{ required: true, message: '请输入应用名称' }],
      icon: [{ required: false }],
      descr: [{ required: true, message: '请输入指令内容' }]
    };

    // ref
    const userFormRef = ref(null);
    //保存或修改
    const isUpdate = ref(false);
    const loading = ref(false);
    const formState = ref({
      name: '',
      icon: '',
      descr: ''
    });
    const emits = defineEmits(['update:visible','ok', 'update-ok']);


    onMounted(async () => {
      isUpdate.value = !!props.data?.isUpdate;
      if (isUpdate.value) {
       formState.value = props.data.record;
      } else {
        isUpdate.value = false;
      }
    });

    const handleCancel = () => {
      emits('update:visible', false); // 通知父组件关闭
    };

    function handleOk() {
      userFormRef.value.validate().then(async valid => {
        if (valid) {
          loading.value = true;
          if (isUpdate.value) {
            emits('update-ok', formState.value);
          } else {
            emits('ok', formState.value);
          }
          loading.value = false;
          handleCancel();
        }
      });
    }

</script>

<style scoped lang="less">
.pointer {
  cursor: pointer;
}
.type-title {
  color: #1d2025;
  margin-bottom: 4px;
}
.type-desc {
  color: #8f959e;
  font-weight: 400;
}
</style>
